import { Table, TableProps, PaginationProps, Pagination } from 'antd';
import { useEffect, useMemo, useRef, useState } from 'react';
import useElementPosition from '@/hooks/use-element-position/useElementPosition';
import NotData from '../NotData';
import { LeftOutlined, RightOutlined } from '@ant-design/icons';

import './tables.scss';
import { cn } from '@/utils/cn-merge';
import { Empty } from '../eai-design';

interface Props<T = any> extends TableProps<T> {
  rowBgClassName?: string;
  paginationProps?: PaginationProps;
  paginationHide?: boolean;
  scroll?: TableProps<T>['scroll'];
  onRow?: TableProps<T>['onRow'];
  rowSelection?: TableProps<T>['rowSelection'];
}

const Tables = <T,>({
  rowBgClassName = 'bg-white',
  paginationHide = false,
  scroll,
  onRow,
  rowSelection,
  ...props
}: Props<T>) => {
  const tableRef = useRef<HTMLDivElement>(null);
  const elementPosition = useElementPosition(tableRef);
  const [hoveredRow, setHoveredRow] = useState<number | null>(null);
  const [selectedRows, setSelectedRows] = useState<number[]>([]);
  const [tableScroll, setTableScroll] = useState<TableProps<T>['scroll']>({});

  const tablesHeader = useRef<HTMLDivElement>(null);

  // 处理rowSelection的onChange事件
  const mergedRowSelection = useMemo(() => {
    if (!rowSelection) return undefined;

    return {
      ...rowSelection,
      onChange: (selectedRowKeys: React.Key[], selectedRows: T[], info: any) => {
        // 获取选中行的索引
        const selectedIndexes = selectedRows
          .map((_, index) => {
            const dataSource = props.dataSource || [];
            return dataSource.findIndex((item) => item === selectedRows[index]);
          })
          .filter((index) => index !== -1);

        setSelectedRows(selectedIndexes);

        // console.log('selectedIndexes', selectedIndexes);

        // 调用外部传入的onChange
        rowSelection.onChange?.(selectedRowKeys, selectedRows, info);
      },
    };
  }, [rowSelection, props.dataSource]);

  const mergedOnRow = useMemo(() => {
    // console.log('selectedRows change', selectedRows);
    return (record: T, index?: number) => {
      // console.log('index', index, selectedRows.includes(Number(index)));
      if (index === undefined) return {};

      const externalProps = onRow?.(record, index) || {};
      return {
        ...externalProps,
        onMouseEnter: (...args: Parameters<NonNullable<typeof externalProps.onMouseEnter>>) => {
          externalProps.onMouseEnter?.(...args);
          setHoveredRow(index);
        },
        onMouseLeave: (...args: Parameters<NonNullable<typeof externalProps.onMouseLeave>>) => {
          externalProps.onMouseLeave?.(...args);
          setHoveredRow(null);
        },
        className: [
          externalProps.className,
          // 如果当前行是悬停行，或者当前行是悬停行的上一行，都添加hide-bottom-border
          // 如果当前行是选中行，或者当前行是选中行的上一行，都添加hide-bottom-border
          selectedRows.includes(Number(index)) ||
          selectedRows.includes(Number(index + 1)) ||
          hoveredRow === index ||
          hoveredRow === index + 1
            ? 'hide-bottom-border'
            : '',
        ]
          .filter(Boolean)
          .join(' '),
      };
    };
  }, [onRow, hoveredRow, selectedRows]);

  useEffect(() => {
    // console.log('tablesHeader', tablesHeader.current?.getBoundingClientRect().height);

    const tablesHeaderHeight = tablesHeader.current?.getBoundingClientRect().height ?? 47;

    const scrollY = `calc(100vh - ${elementPosition.top}px - 80px - 16px - ${tablesHeaderHeight}px)`;

    if (scroll === null) {
      setTableScroll({});
      return;
    }

    if (scroll === undefined) {
      setTableScroll({
        // x: `calc(100vw - ${elementPosition.left}px)`,
        x: 'auto',
        y: scrollY,
      });

      return;
    }

    const result = {
      x: scroll.x,
      // x: scroll.x ? scroll.x : `calc(100vw - ${elementPosition.left}px)`,
      y: scroll.y ? scroll.y : scrollY,
      scrollToFirstRowOnChange: scroll.scrollToFirstRowOnChange,
    };

    setTableScroll(result);
  }, [scroll, elementPosition]);

  // 自定义分页器渲染函数
  const customItemRender = (page: number, type: string, originalElement: React.ReactNode) => {
    const paginationProps = props.paginationProps || {};

    const { current: currentPage = 1, total = 0, pageSize = 10 } = paginationProps;

    const totalPages = Math.ceil(total / pageSize);

    const isPrevDisabled = currentPage <= 1;

    const isNextDisabled = currentPage >= totalPages;

    if (type === 'prev') {
      return (
        <div
          className={`pagination-btn prev-btn flex h-8 w-8 items-center justify-center rounded-md border border-gray-300 bg-[#FDFDFD] px-2  py-1 ${
            isPrevDisabled ? 'cursor-not-allowed  text-gray-400' : 'cursor-pointer'
          }`}
        >
          <LeftOutlined />
        </div>
      );
    }

    if (type === 'next') {
      return (
        <div
          className={`pagination-btn next-btn flex h-8 w-8 items-center justify-center  rounded-md border  border-gray-300 bg-[#FDFDFD] px-2 py-1 ${
            isNextDisabled ? 'cursor-not-allowed  text-gray-400' : 'cursor-pointer'
          }`}
        >
          <RightOutlined />
        </div>
      );
    }
    if (type === 'page') {
      const isCurrent = page === currentPage;
      return (
        <div
          className={`flex h-8 w-8 items-center justify-center rounded-md  ${
            isCurrent
              ? 'border-text-@brand-color text-@brand-color'
              : 'border border-gray-300 bg-white text-gray-700 '
          }`}
        >
          {page}
        </div>
      );
    }

    return originalElement;
  };

  return (
    <div
      className={`rg-table flex h-full flex-col justify-between`}
      style={{
        width: '100%',
        minWidth: 0, // 关键：允许在Flex布局下收缩
        overflow: 'hidden', // 防止内容溢出影响父容器
      }}
      ref={tableRef}
    >
      <Table
        {...props}
        pagination={false}
        className={cn(props.className, 'rg-table')}
        rowClassName={`text-normal text-text-5 ${rowBgClassName}`}
        onRow={mergedOnRow}
        rowSelection={mergedRowSelection}
        scroll={tableScroll}
        components={{
          header: {
            cell: (props: any) => (
              <th
                {...props}
                style={{
                  fontWeight: '600',
                  fontSize: '14px',
                }}
                ref={tablesHeader}
              />
            ),
          },
        }}
        locale={{
          emptyText: (
            <div className="h-full w-full">
              <Empty fontText="暂无数据" />
            </div>
          ),
        }}
      />
      {!paginationHide && (
        // <Pagination
        //   {...props.paginationProps}
        //   showQuickJumper
        //   defaultCurrent={1}
        //   align="end"
        //   showSizeChanger
        //   className="!py-6"
        // />
        <div className="flex items-center justify-between py-6">
          <div className="pagination-total text-text-4">
            共<span className="mx-2">{props.paginationProps?.total || 0}</span>项数据
          </div>

          <Pagination
            {...props.paginationProps}
            defaultCurrent={1}
            showSizeChanger
            showQuickJumper
            itemRender={customItemRender}
          />
        </div>
      )}
    </div>
  );
};

export default Tables;
